<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Backtest</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <style>
        #button-container {
            position: relative;
        }

        #log-button {
            position: absolute;
            top: 0;
            right: 0;
        }
    </style>
</head>
<body>
<div id="button-container">
    <div id="equity" style="width: 1500px;height:900px;"></div>
    <button id="log-button" onclick="change_log()">切换对数坐标</button>
</div>
<script type="text/javascript">
    // prettier-ignore
    option = {
        title: {
            text: '收益&回撤&资金使用率',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                animation: false
            }
        },
        legend: {
            data: ['Equity', 'Draw Down', 'Equity Vs Market Value', 'Benchmark'],
            selected: {
               "Benchmark": false
            },
            left: 10
        },
        toolbox: {
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        axisPointer: {
            link: [
                {
                    xAxisIndex: 'all'
                }
            ]
        },
        dataZoom: [
            {
                show: true,
                realtime: true,
                start: 0,
                end: 100,
                xAxisIndex: [0, 1, 2]
            },
            {
                type: 'inside',
                realtime: true,
                start: 0,
                end: 100,
                xAxisIndex: [0, 1, 2]
            }
        ],
        grid: [
            {
                left: 100,
                right: 50,
                height: '35%'
            },
            {
                left: 100,
                right: 50,
                top: '50%',
                height: '25%'
            },
            {
                left: 100,
                right: 50,
                top: '80%',
                hight: '20%'
                // height: '35%'
            }
        ],
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                axisLine: {onZero: true},
                data: []
            },
            {
                gridIndex: 1,
                type: 'category',
                boundaryGap: false,
                axisLine: {onZero: true},
                show: false,
                data: [],
                // position: 'top'
            },
            {
                gridIndex: 2,
                type: 'category',
                boundaryGap: false,
                axisLine: {onZero: true},
                data: [],
                // position: 'top'
            }
        ],
        yAxis: [
            {
                name: 'Equity log 10',
                type: 'log',
                axisLabel: {  // 科学计数法，对于对数坐标轴，这样可以避免显示一堆0
                    formatter: function (value) {
                        let indexList = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹', '¹⁰', '¹¹', '¹²', '¹³', '¹⁴']
                        if (Math.abs(value) > 10) {
                            if (value === 0)

                                return '0'
                                // 检查是否已经转化为科学计数了
                                // else if ((value + '').indexOf('e') > 0)
                            //   return (value + '').replace(/e/, 'E')
                            else {
                                var res = value.toString()
                                var numN1 = 0
                                var numN2 = 1
                                var num1 = 0
                                var num2 = 0
                                var t1 = 1
                                // 计入小数点前后有多少位
                                for (var k = 0; k < res.length; k++) {
                                    if (res[k] === '.')
                                        t1 = 0
                                    if (t1)
                                        num1++
                                    else
                                        num2++
                                }
                                // 均转换为科学计数法表示
                                if (Math.abs(value) < 1) {
                                    // 小数点后一位开始计算
                                    for (var i = 2; i < res.length; i++) {
                                        if (res[i] === '0')

                                            numN2++ //记录10的负指数值（默认值从1开始）

                                        else if (res[i] === '.')
                                            continue
                                        else
                                            break
                                    }
                                    let v = parseFloat(value)
                                    // 10的numN2次方
                                    v = v * Math.pow(10, numN2)
                                    v = v.toFixed(1) //四舍五入 仅保留一位小数位数
                                    let char = indexList[Number(numN2)]
                                    return v.toString() + '*10' + char
                                } else if (num1 > 1) {
                                    numN1 = num1 - 1
                                    var v = parseFloat(value)
                                    v = v / Math.pow(10, numN1)
                                    if (num2 > 1)

                                        v = v.toFixed(1)

                                    let char = indexList[Number(numN1)]
                                    return v.toString() + '*10' + char
                                }
                            }
                        } else

                            return value
                    }
                },
            },
            {
                gridIndex: 1,
                name: "Draw Down",
                type: 'value',
                // inverse: true
            },
            {
                gridIndex: 2,
                name: 'Equity Vs Market Value',
                type: 'value',
                // inverse: true
            }
        ],
        series: [
            {
                name: 'Equity',
                type: 'line',
                // symbolSize: 8,
                // prettier-ignore
                sampling: 'lttb',
                data: [
                ]
            },
            {
                name: 'Draw Down',
                type: 'line',
                sampling: 'lttb',
                xAxisIndex: 1,
                yAxisIndex: 1,
                color: "black",
                // symbolSize: 8,
                // prettier-ignore
                areaStyle:{
                    origin: "end"
                    },
                data: [
                ]
            },
            {
                name: 'Equity Vs Market Value',
                type: 'line',
                sampling: 'lttb',
                xAxisIndex: 2,
                yAxisIndex: 2,
                // symbolSize: 8,
                // prettier-ignore
                data: [
                ]
            },
            {
                name: 'Benchmark',
                type: 'line',
                sampling: 'lttb',
                // xAxisIndex: 2,
                // yAxisIndex: 2,
                // symbolSize: 8,
                // prettier-ignore
                data: [
                ]
            }
        ]
    };
    console.log(JSON.stringify(option));
    var httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
    httpRequest.open('GET', 'http://{{dic["addr"] }}:{{dic["port"]}}/backtest/data/?strategy={{dic["stg"]}}', true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
    httpRequest.send();//第三步：发送请求  将请求参数写在URL中
    var myChart = echarts.init(document.getElementById('equity'));

    /**
     * 获取数据后的处理程序
     */
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            let json = httpRequest.responseText;//获取到json字符串，还需解析
            let ret = JSON.parse(json);
            // console.log(option);
            // console.log(typeof option);
            // option = eval('(' + option + ')');
            // console.log(option);
            // console.log(typeof option);
            // 基于准备好的dom，初始化echarts实例
            option['xAxis'][0]["data"] = ret['datetime'];
            option['xAxis'][1]["data"] = ret['datetime'];
            option['xAxis'][2]["data"] = ret['datetime'];
            option['series'][0]["data"] = ret['equity'];
            option['series'][1]["data"] = ret['draw_down'];
            option['series'][2]["data"] = ret['equity_vs_market_value'];
            option['series'][3]["data"] = ret['benchmark'];


            option && myChart.setOption(option);
        }
    };

    function change_log(){
        let tp = myChart.getOption()
        if (tp['yAxis'][0]['type'] === 'log'){
            tp['yAxis'][0]['type'] = 'value';
        }else {
            tp['yAxis'][0]['type'] = 'log';
        }
        myChart.setOption(tp)
    }
</script>
</body>
</html>